<template>
  <div>
    <a v-if="displayLink" @click="showModal" class="header-link">
      <a-icon type="setting"/>
      <span>{{ $t('change_password') }}</span>
    </a>
    <a-modal 
      :title="this.$t('change_password')"
      centered
      :maskClosable="false"
      :width="800"
      v-model="visible"
      :okText="$t('modal_submit')"
      :cancelText="$t('modal_cancel')"
      @ok="handleOk"
      :okButtonProps="okButtonProps"
    >
      <a-form :form="form">
        <a-form-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :colon="false" :label="$t('old_password')"
        >
          <a-input
            v-decorator="[
              'oldPassword',
              { rules: [
                  {required: true, message: $t('please_input') + $t('old_password') + $t('exclamation_mark') },
                ]
              }
            ]"
            :placeholder="$t('old_password')"
            type="password"
          />
        </a-form-item>

        <a-form-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :colon="false" :label="$t('new_password')"
        >
          <a-input
            v-decorator="[
              'newPassword',
              { rules: [
                  {required: true, message: $t('please_input') + $t('new_password') + $t('exclamation_mark') },
                  {validator: validateToNextPassword}
                ]
              }
            ]"
            :placeholder="$t('new_password')"
            type="password"
          />
        </a-form-item>

        <a-form-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :colon="false" :label="$t('confirm_new_password')"
        >
          <a-input
            v-decorator="[
              'confirmNewPassword',
              { rules: [
                  {required: true, message: $t('please_input') + $t('confirm_new_password') + $t('exclamation_mark') },
                  {validator: compareToFirstPassword}
                ]
              }
            ]"
            :placeholder="$t('confirm_new_password')"
            type="password"
            @blur="handleConfirmBlur"
          />
        </a-form-item>

      </a-form>
    </a-modal>
  </div>
</template>
<script>
import axios from 'axios'
import qs from 'qs';
import md5 from 'md5'
import JsEncrypt from 'jsencrypt'

export default {
  props: {
    displayLink: { type: [Boolean], default: true },
  },
  data () {
    return {
      form: this.$form.createForm(this, {name: 'PasswordChange'}),
      visible: false,
      confirmDirty: false,
      okButtonProps: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    }
  },
  methods: {
    showModal() {
      this.form.resetFields();
      this.visible = true
      this.okButtonProps = {}
    },
    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form;
      if (value && value !== form.getFieldValue('newPassword')) {
        callback(this.$t('two_password_inconsistent'));
      } else {
        callback();
      }
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form;
      if (value && this.confirmDirty) {
        form.validateFields(['confirmNewPassword'], { force: true });
      }
      callback();
    },
    handleOk() {
      this.form.validateFields((err, formValue) => {
        if (err) {
          return;
        }

        this.okButtonProps ={ props: {disabled: true} }
        // save
        let encrypt = new JsEncrypt()
        encrypt.setPublicKey(this.$store.state.rsaPublicKey)

        axios({
          url: '/infra/security/changePwd',
          method: 'post',
          data: qs.stringify({
            oldPassword: md5(formValue.oldPassword),
            newPassword: encrypt.encrypt(formValue.newPassword),
          }),
        }).then((res) => {
          if (res.data.code == 40010) {
            this.$error({
              title: this.$t('error_message'),
              content: this.$t('old_password_wrong'),
              okText: this.$t('modal_ok'),
            })
            return
          } else if (res.data.code == 400201) {
            this.$error({
              title: this.$t('error_message'),
              content: res.data.msg,
              okText: this.$t('modal_ok'),
            })
            return
          } else if (res.data.code == 400202) {
            this.$error({
              title: this.$t('error_message'),
              content: this.$t(res.data.msg),
              okText: this.$t('modal_ok'),
            })
            return
          }

          this.visible = false
          this.$success({
            title: this.$t('success_message'),
            content: this.$t('submit_success'),
            okText: this.$t('modal_ok'),
          });
        }).finally(() => {
          this.okButtonProps = {}
        });
        
      });
    },
  },
};
</script>
<style scoped>

</style>